<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NSelect,
  NInput,
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  type DataTableColumns,
  NSpace,
  NModal,
  NDatePicker
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VDialogContentOnlySure from '@/views/OA/Common/DialogContentOnlySure.vue'
import { RecordType } from '@/router/utils'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()


const formInfo: any = reactive({
  archiveStatus: null,
  docContractName: null
})

const StatusList = [
  {
    value: 1,
    label: '待盖章',
  },
  {
    value: 2,
    label: '已盖章待归档',
  },
  {
    value: 3,
    label: '已归档待确认',
  },
  {
    value: 4,
    label: '已归档',
  },
]

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '用户',
    key: 'userName',
    width: '5rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '部门',
    key: 'deptName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '用章名称',
    key: 'chapterName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '用章数量',
    key: 'chapterCategoryNum',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '合同/文件名称',
    key: 'docContractName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '用途',
    key: 'useInfo',
    width: '10rem',
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '申请时间',
    key: 'applicationTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '盖章时间',
    key: 'categoryTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '归档时间',
    key: 'filingTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'approvalStatus',
    width: '10rem',
    align: useStore.isCenter,
    render({ status }) {
      switch (status) {
        case 1:
          return '待盖章'
        case 2:
          return '已盖章待归档'
        case 3:
          return '已归档待确认'
        case 4:
          return '已归档'
      }
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '15rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0507')
            handleDetail(e)
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          style: {
            display: e.status == 1 ? 'inline-flex' : 'none'
          },
          onClick: () => handleSeal(e)
        },
        {
          default: () => '完成盖章'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          style: {
            display: e.status == 3 ? 'inline-flex' : 'none'
          },
          onClick: () => handleSure(e)
        },
        {
          default: () => '确认归档'
        }
      )
    ]
  }
]

//日期选择器
const timeRange = ref()
const changeTime = (e: any) => {
  if (e) {
    formValue.startTime = e[0]
    formValue.endTime = e[1]
  } else {
    formValue.startTime = null
    formValue.endTime = null
  }
}

//筛选条件
const formValue = reactive({
  startTime: null,
  endTime: null
})
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Seal/SealMakeSureDetail',
    query: {
      id: val.id
    }
  })
}

//确定盖章
const sealVisiable = ref(false)
const finishNoticeVisible = ref(false)
const modalId = ref()
const handleSeal = async (val: any) => {
  modalId.value = val?.id
  sealVisiable.value = true
}
const againSeal = async () => {
  const [error, res] = await sendRequest({
    module: 'seal',
    api: 'makeSure',
    override: {
      params: {
        id: modalId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    message.error(res.data)
  } else {
    message.success(res.data)
    sealVisiable.value = false
    finishNoticeVisible.value = true
    queryTableData(true)
  }
}

const finishNotice = () => {
  finishNoticeVisible.value = false
}

//确定归档
const sureVisiable = ref(false)
const handleSure = async (val: any) => {
  modalId.value = val?.id
  sureVisiable.value = true
}
const againSure = async () => {
  const [error, res] = await sendRequest({
    module: 'seal',
    api: 'makeSureOk',
    override: {
      params: {
        id: modalId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code) {
    message.error(res.data)
  } else {
    message.success(res.data)
    sureVisiable.value = false
    queryTableData(true)
  }
}



//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'seal',
    api: 'sealApplicationList',
    override: {
      params: {
        ...formInfo,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        startTime: formValue.startTime,
        endTime: formValue.endTime,
        statusCode: 'A0605',
        chapterCategoryCode: 'A0508' //法人章/馆章/馆党委章
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))


watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Seal/sealMakeSure') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="申请时间:">
            <NDatePicker input-readonly type="datetimerange" default-time="00:00:00" clearable v-model:value="timeRange"
              :on-update:formatted-value="changeTime" />
          </NFormItem>
          <NFormItem label="状态:">
            <NSelect v-model:value="formInfo.archiveStatus" :options="StatusList" style="width:150px" clearable
               />
          </NFormItem>
          <NFormItem label="合同/文件名称:">
            <NInput v-model:value="formInfo.docContractName" clearable />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" style="width: 78px; margin-right: 40rem" ghost @click="queryTableData(true)">
              查询
            </NButton>
          </NFormItem>
        </NForm>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="sealVisiable">
    <VDialogContent @close="sealVisiable = false" @submit="againSeal" title="完成盖章提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要完成盖章吗?
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="sureVisiable">
    <VDialogContent @close="sureVisiable = false" @submit="againSure" title="确认归档提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要确认归档吗?
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="finishNoticeVisible">
    <VDialogContentOnlySure @close="finishNoticeVisible = false" @submit="finishNotice" title="提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        盖章已完成，请尽快完成归档
      </div>
    </VDialogContentOnlySure>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
